/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: app2022 - T31
 * <p>Powered by webrx On 2022-02-08 14:07:27
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T31 {
    AtomicInteger atomicCount = new AtomicInteger(0);
    int count = 0;

    public static void main(String[] args) {
        var t1 = new T31();

        //atomicxx
        long time1 = time(t1::m);
        System.out.println(t1.atomicCount);

        //synchronized
        long time2 = time(t1::m2);
        System.out.println(t1.count);

        try {
            TimeUnit.SECONDS.sleep(12);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.print("AtomicXxx:");
        System.out.println(time1);
        System.out.print("synchronized:");
        System.out.println(time2);
    }


    private static long times(Runnable runnable) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new Thread(runnable, "thread-" + i).start();
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }
    
    private static long time(Runnable runnable) {
        List<Thread> threads = new ArrayList<>();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(runnable, "thread-" + i));
        }
        threads.forEach(Thread::start);
        threads.forEach(o -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

    void m() {
        for (int i = 0; i < 1000000; i++) {
            atomicCount.incrementAndGet(); //原子操作
        }
    }

    void m2() {
        for (int i = 0; i < 1000000; i++) {
            synchronized (this) {
                count++;
            }
        }
    }
}
